<template>
  <div class="history-analysis">
    <h3 class="section-title">历史作业分析</h3>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="historyData.length === 0" class="no-data">
      <el-empty description="该日期暂无作业记录" />
    </div>

    <div v-else class="analysis-content">
      <div
        v-for="record in historyData"
        :key="record.id"
        class="homework-record"
      >
        <div class="record-header">
          <h4 class="record-title">{{ record.title }}</h4>
          <el-tag :type="getStatusType(record.status)">
            {{ getStatusText(record.status) }}
          </el-tag>
        </div>

        <div class="record-details">
          <div class="detail-item">
            <span class="label">开始时间：</span>
            <span class="value">{{ formatBeginDateTime(record) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">完成时间：</span>
            <span class="value">{{ formatEndDateTime(record) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">作业进度：</span>
            <span class="value">{{ record.completed_items }}/{{ record.total_items }}</span>
          </div>
          <div v-if="record.duration" class="detail-item">
            <span class="label">完成耗时：</span>
            <span class="value">{{ formatDuration(record.duration) }}</span>
          </div>
        </div>

        <div class="progress-bar">
          <el-progress
            :percentage="getProgressPercentage(record)"
            :color="getProgressColor(record.status)"
            :stroke-width="8"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { analyticsApi } from '@/api/analytics'
import dayjs from 'dayjs'

const props = defineProps({
  selectedDate: {
    type: [Date, String],
    default: () => new Date()
  },
  studentId: {
    type: Number,
    required: true
  }
})

const loading = ref(false)
const historyData = ref([])

const formattedDate = computed(() => {
  const date = dayjs(props.selectedDate)
  return {
    year: date.year(),
    month: date.month() + 1,
    day: date.date()
  }
})

const loadHistoryData = async () => {
  if (!props.studentId) {
    return
  }

  try {
    loading.value = true
    const selectedDateStr = dayjs(props.selectedDate).format('YYYY-MM-DD')
    console.log('🔍 历史分析 - 查询日期:', selectedDateStr, '学生ID:', props.studentId)
    console.log('📅 查询参数 - 年:', formattedDate.value.year, '月:', formattedDate.value.month)

    const response = await analyticsApi.getHomeworkRecords(
      props.studentId,
      formattedDate.value.year,
      formattedDate.value.month
    )

    console.log('📥 历史数据API响应:', response.data)

    // 历史记录API直接返回数组，不像日历API那样嵌套在data字段中
    const actualData = response.data || []
    console.log('📊 历史数据总记录数量:', actualData.length)

    if (actualData.length === 0) {
      console.log('❌ 没有找到任何历史记录')
      historyData.value = []
      return
    }

    // 显示所有记录的日期信息
    console.log('📋 所有历史记录日期:')
    actualData.forEach((record, index) => {
      console.log(`  ${index + 1}. ${record.title} - ${record.date} (状态: ${record.status})`)
    })

    // 过滤匹配选中日期的记录
    historyData.value = actualData.filter(record => {
      if (!record.date) {
        console.log('⚠️ 跳过无日期的记录:', record)
        return false
      }

      const recordDateStr = dayjs(record.date).format('YYYY-MM-DD')
      const isMatch = recordDateStr === selectedDateStr

      if (isMatch) {
        console.log('✅ 找到匹配的历史记录:', record.title, '日期:', recordDateStr)
      }

      return isMatch
    })

    console.log('🎯 选中日期', selectedDateStr, '的历史记录:', historyData.value.length, '条')
  } catch (error) {
    console.error('❌ 加载历史数据失败:', error)
    ElMessage.error('加载历史数据失败')
    historyData.value = []
  } finally {
    loading.value = false
  }
}

const formatBeginDateTime = (homework) => {
  if (!(homework.actual_start_time)) return '未开始'
  return dayjs(homework.actual_start_time).format('HH:mm')
}

const formatEndDateTime = (homework) => {
  if (!(homework.actual_start_time)) return '未开始'
  else if(!(homework.actual_end_time)) return '未完成'
  return dayjs(homework.actual_end_time).format('HH:mm')
}





const formatDuration = (duration) => {
  if (!duration) return '-'
  // duration 格式为 "HH:mm:ss"
  const [hours, minutes, seconds] = duration.split(':')
  const totalMinutes = parseInt(hours) * 60 + parseInt(minutes)
  if (totalMinutes < 60) {
    return `${totalMinutes}分钟`
  } else {
    const h = Math.floor(totalMinutes / 60)
    const m = totalMinutes % 60
    return `${h}小时${m}分钟`
  }
}

const getStatusType = (status) => {
  const types = {
    0: 'info',    // 未开始
    1: 'warning', // 进行中
    2: 'success'  // 已完成
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    0: '未开始',
    1: '进行中',
    2: '已完成'
  }
  return texts[status] || '未知'
}

const getProgressPercentage = (record) => {
  if (!record.total_items || record.total_items === 0) return 0
  return Math.round((record.completed_items / record.total_items) * 100)
}

const getProgressColor = (status) => {
  const colors = {
    0: '#909399', // 灰色 - 未开始
    1: '#e6a23c', // 橙色 - 进行中
    2: '#67c23a'  // 绿色 - 已完成
  }
  return colors[status] || '#909399'
}

// 监听选中日期变化
watch(() => props.selectedDate, () => {
  loadHistoryData()
}, { immediate: true })

// 监听学生ID变化
watch(() => props.studentId, () => {
  if (props.studentId) {
    loadHistoryData()
  }
}, { immediate: true })
</script>

<style scoped>
.history-analysis {
  height: 100%;
  min-width: 280px; /* 防止分析区域过度压缩 */
}

.section-title {
  font-size: clamp(16px, 3vw, 18px);
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.loading-container {
  padding: 20px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.analysis-content {
  max-height: 400px;
  overflow-y: auto;
}

.homework-record {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  border-left: 4px solid #3b82f6;
}

.homework-record:last-child {
  margin-bottom: 0;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 8px;
}

.record-title {
  font-size: clamp(14px, 2.5vw, 16px);
  font-weight: bold;
  margin: 0;
  color: #333;
  flex: 1;
  min-width: 0; /* 允许文本换行 */
}

.record-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  margin-bottom: 12px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  font-size: clamp(12px, 2vw, 14px);
  flex-wrap: wrap;
}

.label {
  color: #666;
  margin-right: 8px;
  min-width: 80px;
  flex-shrink: 0;
}

.value {
  color: #333;
  font-weight: 500;
  flex: 1;
  word-break: break-word;
}

.progress-bar {
  margin-top: 12px;
}

/* 平板设备适配 */
@media (max-width: 1024px) {
  .history-analysis {
    min-width: 250px;
  }

  .record-details {
    grid-template-columns: 1fr;
    gap: 6px;
  }

  .detail-item {
    margin-bottom: 6px;
  }

  .label {
    min-width: 70px;
    font-size: 13px;
  }
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .history-analysis {
    min-width: 220px;
  }

  .section-title {
    font-size: 16px;
    margin-bottom: 16px;
  }

  .homework-record {
    padding: 12px;
    margin-bottom: 12px;
  }

  .record-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }

  .record-title {
    font-size: 14px;
    width: 100%;
  }

  .record-details {
    grid-template-columns: 1fr;
    gap: 6px;
  }

  .detail-item {
    margin-bottom: 6px;
    font-size: 13px;
  }

  .label {
    min-width: 70px;
    font-size: 12px;
  }

  .value {
    font-size: 13px;
  }
}

/* 小屏幕设备适配 */
@media (max-width: 480px) {
  .history-analysis {
    min-width: 200px;
  }

  .section-title {
    font-size: 14px;
    margin-bottom: 12px;
  }

  .homework-record {
    padding: 10px;
    margin-bottom: 10px;
  }

  .record-title {
    font-size: 13px;
  }

  .label {
    min-width: 65px;
    font-size: 11px;
    margin-right: 6px;
  }

  .value {
    font-size: 12px;
  }

  .detail-item {
    font-size: 12px;
  }

  .analysis-content {
    max-height: 350px;
  }
}
</style>